package com.sgb.kjwl.view.ui.fragment.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentGoodsMainGoodsList2Binding;
import com.sgb.kjwl.di.material.DaggerMaterialFragComponent;
import com.sgb.kjwl.di.material.MaterialFragModule;
import com.sgb.kjwl.model.entity.GoodsListTypeEntity;
import com.swgk.core.util.StringUtil;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.AreaChooseEntity;
import com.sgb.kjwl.model.entity.user.GoodsListEntity;
import com.sgb.kjwl.model.entity.user.MaterChooseEntity;
import com.sgb.kjwl.model.entity.user.RecommendListEntity;
import com.sgb.kjwl.model.entity.user.TwoOrThreeLevelEntity;
import com.sgb.kjwl.utils.ActivityClassHelper;
import com.sgb.kjwl.utils.LocationUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.link.event.MaterialEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.home.HomeCategoryActivity;
import com.sgb.kjwl.view.ui.activity.material.ConcreteDetailActivity2;
import com.sgb.kjwl.view.ui.activity.material.GoodsAggregateActivity;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopGoodsDetailActivity;
import com.sgb.kjwl.view.ui.adapter.search.MaterialAdapter;
import com.sgb.kjwl.view.ui.adapter.search.MatterChooseAdapter;
import com.sgb.kjwl.view.ui.adapter.search.RecommendGoodsAdapter;
import com.sgb.kjwl.view.ui.adapter.search.RecommendMatterChooseAdapter;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.MatterChooseMaterialFliterPopWindow3;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.transport.MatterChooseWindow;
import com.sgb.kjwl.viewmodel.home.GoodsMainGoodsListModel2;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.base.model.entity.RequestCode;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;

import javax.inject.Inject;

/**
 * @author 说明：促销、热销商品页面
 * <p>
 * 说明：2021.07.19 已弃用 使用GoodsMainGoodsListFragment4代替
 */
@Deprecated
public class GoodsMainGoodsListFragment2 extends AppFragment {

    @Inject
    GoodsMainGoodsListModel2 mModel;
    private FragmentGoodsMainGoodsList2Binding mBinding;
    private String mLon = "0";
    private String mLat = "0";
    private MatterChooseMaterialFliterPopWindow3 mPopWindow;
    private DictWindow5 distanceWindow5;
    private String distanceId = "";
    private List<MenuEntity> mGoodsType;
    private int mPageNum = 1;
    private String mDistance = "";
    private String mPriceSort = "0";
    private String mCid1 = "";
    private String mCid3 = "";
    private String mCategoryId = "";
    private List<String> mBrandId = new ArrayList<>();
    private List<String> mMaterValue = new ArrayList<>();
    private boolean isLoadMoreGoodsList;
    private boolean isLoadMoreRecommendGoodsList;
    private MaterialAdapter mMaterialAdapter;
    private List<String> mAreaId = new ArrayList<>();
    private String mCityId = "";
    private String mProvince = "";
    private int mRecommendPageNum = 0;
    private String mRecommendValId = "";
    private String mItemCid1 = "";
    private String mItemCid2 = "";
    private String mItemCid3 = "";
    private RecommendGoodsAdapter mRecommendGoodsAdapter;
    private ThreeLevelAreaWindow mThreeLevelPopWindow;
    private int type;
    private MatterChooseAdapter mMatterChooseAdapter;
    private RecommendMatterChooseAdapter mRecommendMatterChooseAdapter;
    private int mSelectType = 0;
    private int mSelectTab = 0;
    private List<TwoOrThreeLevelEntity> mTwo;
    private List<TwoOrThreeLevelEntity> mThree;
    private List<DictEntity3> mDistanceData;
    private String mArea = "";
    private String mDistanceName = "";
    private String mOneType, mTwoType, mThreeType;
    private Map<String, MaterChooseEntity.TypeBean> mRecommendStr = new HashMap<>();
    private Map<String, MaterChooseEntity.TypeBean> mStr = new HashMap<>();
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> mAreaList = new ArrayList<>();
    /***
     * 是否是自营产品
     */
    private boolean isZiYingChecked = false;
    /***
     * 是否是热销产品
     */
    private boolean isSellGoodGoods = false;

    /***
     *
     * true 促销商品 false 非促销商品
     */
    private boolean isPromotionalGoods = false;

    private boolean isStartAct1 = true;//第2层的定位标识
    private boolean isStartAct2 = true;//弟3层的定位标识
    /****
     * 是否重置定位
     */
    private boolean isRePositioning;

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMaterialFragComponent.builder()
                .appComponent(appComponent)
                .materialFragModule(new MaterialFragModule(this))
                .build()
                .inject(this);
    }

    public static GoodsMainGoodsListFragment2 newInstance(int type, List<MenuEntity> goodsType, int position, boolean promotionalGoods, boolean isSellGoodGoods) {
        GoodsMainGoodsListFragment2 goodsMainGoodsListFragment = new GoodsMainGoodsListFragment2();
        Bundle bundle = new Bundle();
        bundle.putInt("goodsListType", type);
        bundle.putSerializable("goodsList", (Serializable) goodsType);
        bundle.putInt("childPosition", position);
        bundle.putBoolean("promotionalGoods", promotionalGoods);
        bundle.putBoolean("isSellGoodGoods", isSellGoodGoods);
        goodsMainGoodsListFragment.setArguments(bundle);
        return goodsMainGoodsListFragment;
    }

    public static GoodsMainGoodsListFragment2 newInstance(int type, List<MenuEntity> goodsType, int position, String province) {
        GoodsMainGoodsListFragment2 goodsMainGoodsListFragment = new GoodsMainGoodsListFragment2();
        Bundle bundle = new Bundle();
        bundle.putInt("goodsListType", type);
        bundle.putSerializable("goodsList", (Serializable) goodsType);
        bundle.putInt("childPosition", position);
        bundle.putString("province", province);
        goodsMainGoodsListFragment.setArguments(bundle);
        return goodsMainGoodsListFragment;
    }

    public static GoodsMainGoodsListFragment2 newInstance(int type, List<MenuEntity> goodsType, int position, String mOne, String mTwo, String mThree) {
        GoodsMainGoodsListFragment2 goodsMainGoodsListFragment = new GoodsMainGoodsListFragment2();
        Bundle bundle = new Bundle();
        bundle.putInt("goodsListType", type);
        bundle.putSerializable("goodsList", (Serializable) goodsType);
        bundle.putInt("childPosition", position);
        bundle.putString("one", mOne);
        bundle.putString("two", mTwo);
        bundle.putString("three", mThree);
        goodsMainGoodsListFragment.setArguments(bundle);
        return goodsMainGoodsListFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_goods_main_goods_list2, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        assert getArguments() != null;
        type = getArguments().getInt("goodsListType");
        mGoodsType = (List<MenuEntity>) getArguments().getSerializable("goodsList");
        int position = getArguments().getInt("childPosition");
        mOneType = getArguments().getString("one");
        mTwoType = getArguments().getString("two");
        mThreeType = getArguments().getString("three");
        mProvince = getArguments().getString("province");
        isSellGoodGoods = getArguments().getBoolean("isSellGoodGoods", false);
        isPromotionalGoods = getArguments().getBoolean("promotionalGoods", false);
        if (mProvince == null) {
            mProvince = "";
        }
        mProvince = mModel.getAreaCode();
        mBinding.setGoodsFragment(this);
        GoodsListTypeEntity typeEntity = ActivityClassHelper.getGoodsListStyle(getContext(), type);
        if (isSellGoodGoods) {
            typeEntity.setHaveFilter(false);
        }
        mBinding.setGoodsType(typeEntity);
        mBinding.setGoodsModel(mModel);

        if (type == 0) {
            for (MenuEntity menuEntity : mGoodsType) {
                mBinding.tlFragmentGoodsMainGoodsSelectTitle1.addTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.newTab().setText(menuEntity.getName()));
            }
        } else {
            mModel.getMenuModel("");
        }
        if (type == 1) {
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mBinding.xrvFragmentGoodsMainGoodsList.getLayoutParams();
            lp.setMargins(0, 20, 0, 0);
            mBinding.xrvFragmentGoodsMainGoodsList.setLayoutParams(lp);
        }

        if (mOneType != null && !"".equals(mOneType)) {
            mCid1 = mOneType;
            mCategoryId = mTwoType;
            mCid3 = mThreeType;
            for (int i = 0; i < mGoodsType.size(); i++) {
                if (mGoodsType.get(i).getId().equals(mOneType)) {
                    int finalI = i;
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle1.postDelayed(() -> Objects.requireNonNull(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.getTabAt(finalI)).select(), 100);
                }
            }
            mSelectTab = 1;
            mModel.getTwoOrThreeLevelData(mOneType);
            mBinding.tvFragmentGoodsMainGoodsListSelect2.setVisibility(View.VISIBLE);
        } else {
            mBinding.tlFragmentGoodsMainGoodsSelectTitle1.setScrollPosition(position, 0, true);
            mBinding.tvFragmentGoodsMainGoodsListSelect2.setVisibility(View.GONE);
        }
        mBinding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.GONE);
        mBinding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.GONE);
        mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
        mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);


        mBinding.tlFragmentGoodsMainGoodsSelectTitle1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setCurrentTab(tab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        mBinding.tlFragmentGoodsMainGoodsSelectTitle2.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    mBinding.rlGoodMatterChoose.setVisibility(View.GONE);
                    mBinding.rvGoodMatterChoose.setVisibility(View.GONE);
                    if (type == 0) {
                        mItemCid2 = "";
                        mItemCid3 = "";
                        mRecommendValId = "";
                    } else {
                        mCid3 = "";
                        mCategoryId = "";
                        mMaterValue.clear();
                    }
                }

                String id;
                if (type == 0) {
                    mItemCid2 = mTwo.get(tab.getPosition()).getId();
                    id = mItemCid2;
                } else {
                    mCategoryId = mTwo.get(tab.getPosition()).getId();
                    id = mCategoryId;
                }


                if (tab.getPosition() == 0) {
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
                    mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
                } else {
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.VISIBLE);
                    mBinding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.VISIBLE);
                    mSelectType = 1;
                    mSelectTab = 1;
                    mModel.getTwoOrThreeLevelData(id);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        mBinding.tlFragmentGoodsMainGoodsSelectTitle3.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String cid;
                if (type == 0) {
                    mItemCid3 = mThree.get(tab.getPosition()).getId();
                    loadRecommendList(false);
                    cid = mItemCid3;
                } else {
                    mCid3 = mThree.get(tab.getPosition()).getId();
                    loadAllList(false);
                    cid = mCid3;
                }
                mBinding.rlGoodMatterChoose.setVisibility(View.VISIBLE);
                mBinding.rvGoodMatterChoose.setVisibility(View.VISIBLE);
                mModel.getMaterialBrand(cid);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        initFilterView();
        mModel.getAreaData();
        mModel.getPriceSort();
        mModel.getAreaChoose();

        MaterialHomeFragment materialHomeFragment = (MaterialHomeFragment) getParentFragment();
        if (type == 0) {
            mModel.getFilterDistance(mItemCid1);
            mBinding.xrvFragmentGoodsMainGoodsList.setLayoutManager(new GridLayoutManager(getContext(), 2));
            mRecommendGoodsAdapter = new RecommendGoodsAdapter(getContext(), null);
            mBinding.xrvFragmentGoodsMainGoodsList.setAdapter(mRecommendGoodsAdapter);
            mRecommendGoodsAdapter.setmResembleGoodsClick(recommendListEntity -> {
                //assert materialHomeFragment != null;
                //materialHomeFragment.startForResemble(recommendListEntity.getCid1(), recommendListEntity.getCid2(), recommendListEntity.getCid(), 0);
            });
            mRecommendGoodsAdapter.setOnItemClick(new AdapterOnItemClick<RecommendListEntity>() {
                @Override
                public void onItemClick(RecommendListEntity recommendListEntity, int position) {
                    if ("7".equals(mGoodsType.get(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.getSelectedTabPosition()).getId())) {
                        ConcreteDetailActivity2.start(getActivity(), recommendListEntity.getId());
                    } else {
                        ShopGoodsDetailActivity.start(getContext(), recommendListEntity.getId(), "", recommendListEntity.getSkuid());
                    }
                }
            });
            loadRecommendList(false);
        } else {
            mModel.getFilterDistance(mCid1);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            mBinding.xrvFragmentGoodsMainGoodsList.setLayoutManager(linearLayoutManager);
            mMaterialAdapter = new MaterialAdapter(getContext(), null,false);
            mBinding.xrvFragmentGoodsMainGoodsList.setAdapter(mMaterialAdapter);
            mMaterialAdapter.setOnItemClick(new AdapterOnItemClick<GoodsListEntity>() {
                @Override
                public void onItemClick(GoodsListEntity goodsListEntity, int position) {
                    if ("7".equals(mGoodsType.get(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.getSelectedTabPosition()).getId())) {
                        ConcreteDetailActivity2.start(getActivity(), goodsListEntity.getId());
                    } else {
                        ShopGoodsDetailActivity.start(getContext(), goodsListEntity.getId(), "", goodsListEntity.getSkuid());
                    }
                }
            });
            mBinding.xrvFragmentGoodsMainGoodsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (linearLayoutManager.findFirstVisibleItemPosition() > 1) {
                        mBinding.imgBackTop.setVisibility(View.VISIBLE);
                    } else {
                        mBinding.imgBackTop.setVisibility(View.GONE);
                    }
                }
            });
            loadAllList(false);
        }

        if (type == 0) {
            mBinding.xrvFragmentGoodsMainGoodsList.setPullRefreshEnabled(false);
        }

        mBinding.xrvFragmentGoodsMainGoodsList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadAllList(false);
            }

            @Override
            public void onLoadMore() {
                if (type == 0) {
                    loadRecommendList(true);
                } else {
                    loadAllList(true);
                }
            }
        });

        mBinding.tvFragmentGoodsMainGoodsListSelect2.setOnClickListener(this);
        mBinding.tvFragmentGoodsMainGoodsListSelect1.setOnClickListener(this);
        mBinding.imgBackTop.setOnClickListener(this);
        mBinding.ivGoodsListSearch.setOnClickListener(this);
        mBinding.llContent.setOnClickListener(this::onMultiClick);
        mBinding.tvGoodsListScreen.setOnClickListener(this);
        LinearLayoutManager la = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        mBinding.rvGoodMatterChoose.setLayoutManager(la);

        if (type == 0) {
            mRecommendMatterChooseAdapter = new RecommendMatterChooseAdapter(getContext(), null);
            mBinding.rvGoodMatterChoose.setAdapter(mRecommendMatterChooseAdapter);
            mRecommendMatterChooseAdapter.setmMatterChoose((entity, select) -> {
                select.contentSelectRed(false, true);
                StringBuilder mList = new StringBuilder();
                final String[] name = {""};
                MatterChooseWindow mNameWindow5 = new MatterChooseWindow(getContext());
                boolean isChange = false;

                mNameWindow5.setOnCloseBack(() -> {
                    if (!name[0].equals("")) {
                        select.contentSelectRed(true, true);
                    } else {
                        select.contentSelectRed(false, false);
                    }
                });

                mNameWindow5.setOnCallBack(dictEntity -> {
                    mRecommendStr.put(entity.getName(), dictEntity);
                    for (MaterChooseEntity.TypeBean value : mRecommendStr.values()) {
                        mList.append(",").append(value.getCid());
                    }
                    mList.replace(0, 1, "");
                    name[0] = dictEntity.getCname();

                    mRecommendValId = mList.toString();
                    loadRecommendList(false);
                });

                mNameWindow5.setData(entity.getType());
                mNameWindow5.setBgView(mBinding.grayLayout);
                for (String s : mRecommendStr.keySet()) {
                    if (entity.getName().equals(s)) {
                        mNameWindow5.setCheckDefaultById(Objects.requireNonNull(mRecommendStr.get(s)).getCid());
                        isChange = true;
                        break;
                    } else {
                        isChange = false;
                    }
                }

                if (!isChange) {
                    mNameWindow5.setCheckDefaultById(entity.getType().get(0).getCid());
                }
                mNameWindow5.showPopwindow(mBinding.nsvSelect, 0, 0);
            });
        } else {
            mMatterChooseAdapter = new MatterChooseAdapter(getContext(), null);
            mBinding.rvGoodMatterChoose.setAdapter(mMatterChooseAdapter);
            mMatterChooseAdapter.setmMatterChoose((entity, select) -> {
                select.contentSelectRed(false, true);
                List<String> mList = new ArrayList<>();
                final String[] name = {""};
                boolean isChange = false;
                MatterChooseWindow mNameWindow5 = new MatterChooseWindow(getContext());

                mNameWindow5.setOnCloseBack(() -> {
                    if (!name[0].equals("")) {
                        select.contentSelectRed(true, true);
                    } else {
                        select.contentSelectRed(false, false);
                    }
                });

                mNameWindow5.setOnCallBack(dictEntity -> {
                    mStr.put(entity.getName(), dictEntity);
                    for (MaterChooseEntity.TypeBean value : mStr.values()) {
                        mList.add(value.getCname());
                    }

                    name[0] = dictEntity.getCname();
                    mMaterValue = mList;
                    loadAllList(false);
                });

                mNameWindow5.setData(entity.getType());
                mNameWindow5.setBgView(mBinding.grayLayout);
                for (String s : mStr.keySet()) {
                    if (entity.getName().equals(s)) {
                        mNameWindow5.setCheckDefaultById(Objects.requireNonNull(mStr.get(s)).getCid());
                        isChange = true;
                        break;
                    } else {
                        isChange = false;
                    }
                }

                if (!isChange) {
                    mNameWindow5.setCheckDefaultById(entity.getType().get(0).getCid());
                }
                mNameWindow5.showPopwindow(mBinding.nsvSelect, 0, 0);
            });


        }
    }

    public void showMenuView(List<MenuEntity> data) {
//        this.mGoodsType = data;
//        for (MenuEntity datum : data) {
//            if (!"7".equals(datum.getId())) {
//                mBinding.tlFragmentGoodsMainGoodsSelectTitle1.addTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.newTab().setText(datum.getName()));
//
//            }
//        }
        if (data != null && data.size() != 0) {
            ListIterator<MenuEntity> iterator = data.listIterator();
            while (iterator.hasNext()) {
                MenuEntity menuEntity = iterator.next();
                if ("7".equals(menuEntity.getId())) {
                    iterator.remove();
                } else {
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle1.addTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.newTab().setText(menuEntity.getName()));
                }
            }
            this.mGoodsType = data;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 102 && data != null) {
            mLat = String.valueOf(data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0));
            mLon = String.valueOf(data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0));
            isRePositioning = true;
            loadAllList(false);
        }
    }


    public void locationClick() {
        Intent intent = new Intent();
        intent.setClass(requireContext(), SelectAddressActivity.class);
        intent.putExtra(SelectAddressActivity.TITLE, "选择定位地址");
        intent.putExtra(SelectAddressActivity.LATITUDE, Double.valueOf(mLat));
        intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.valueOf(mLon));
        startActivityForResult(intent, 102);
    }

    private void initFilterView() {
        mThreeLevelPopWindow = new ThreeLevelAreaWindow(getContext()) {
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                if (!mProvince.equals(baseAreaEntity.getId())) {
                    mCityId = "";
                }
                mProvince = baseAreaEntity.getId();
                mArea = baseAreaEntity.getName();
                if (mAreaId != null) {
                    mAreaId.clear();
                }
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                if (!mCityId.equals(baseAreaEntity.getId())) {
                    mAreaId.clear();
                    mArea = "";
                }
                mCityId = baseAreaEntity.getId();
                mArea = baseAreaEntity.getName();
            }

            @Override
            protected void areaMoreClick(List list, int position) {
                for (Object o : list) {
                    BaseAreaEntity baseAreaEntity = (BaseAreaEntity) o;
                    mAreaId.add(baseAreaEntity.getId());
                    mArea = baseAreaEntity.getName();
                }
            }
        };
        mThreeLevelPopWindow.setShowSimpleName(true);
        mThreeLevelPopWindow.setBgView(mBinding.grayLayout);
        if (type == 0) {
            mThreeLevelPopWindow.setLayoutPadding(10, 10);
        }
        mThreeLevelPopWindow.setAreaMore();
        mThreeLevelPopWindow.setCitySingle();
        mThreeLevelPopWindow.setProvinceSingle();
        mThreeLevelPopWindow.setOnResultClick((key1, key2, key3) -> {
            if (type == 0) {
                loadRecommendList(false);
            } else {
                loadAllList(false);
            }
        });
        mThreeLevelPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (mArea.equals("") || mArea.equals("不限")) {
                    mBinding.tvFragmentGoodsMainGoodsListSelect1.contentSelectRed(false, false);
                } else {
                    mBinding.tvFragmentGoodsMainGoodsListSelect1.contentSelectRed(true, false);
                }
            }
        });

        distanceWindow5 = new DictWindow5(getActivity(), 1);
        distanceWindow5.setBgView(mBinding.grayLayout);
        distanceWindow5.setOnCallBack(dictEntity -> {
            mDistance = dictEntity.getId();
            mDistanceName = dictEntity.getName();
            Objects.requireNonNull(mModel.materialFilterJson.get()).setDistance(dictEntity.getName());
            mPopWindow.setDistanceDefault(distanceWindow5.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
        });
        distanceWindow5.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (mDistanceName.equals("") || mDistanceName.equals("不限")) {
                    mBinding.tvFragmentGoodsMainGoodsListSelect2.contentSelectRed(false, false);
                } else {
                    mBinding.tvFragmentGoodsMainGoodsListSelect2.contentSelectRed(true, false);
                }
            }
        });

        mPopWindow = new MatterChooseMaterialFliterPopWindow3(getActivity());
        mPopWindow.setBgView(mBinding.grayLayout);
        mPopWindow.setFilterResultClick(new MatterChooseMaterialFliterPopWindow3.FilterResultClick() {
            @Override
            public void result(MaterialFilterJson materialFilterJson, List<DictEntity3> data, SparseBooleanArray checkBooleanArray) {
                mAreaId = materialFilterJson.getAreaList();
                mBrandId = materialFilterJson.getBrandId();
                mCategoryId = materialFilterJson.getCategoryId();
                mCid3 = materialFilterJson.getItemId();
                mMaterValue = materialFilterJson.getMaterValue();
                mDistance = materialFilterJson.getDistance();
                mPriceSort = String.valueOf(materialFilterJson.getPriceSort());
                loadAllList(false);

                distanceId = materialFilterJson.getDistance();
                distanceWindow5.setCheckDefaultById(distanceWindow5.getCheckDefultId(distanceId));

            }

            @Override
            public void queryTypeClassid(String id) {

            }

            @Override
            public void queryTypeChild(String id) {
                mModel.getTwoOrThreeLevelData(id);
                mSelectType = 1;
            }

            @Override
            public void queryNameChild(String id) {
                //品牌
                mModel.getFilterBrandModel(id);
                //sku属性
                mModel.getMaterialBrand(id);
            }
        });

        mPopWindow.setOnDisMissClick(() -> EventBus.getDefault().post(LeaseEvent.make().setMessageTag(EventConstant.EVENT_SHOP_VISIBLE)));
    }

    public void showBrandPopWindow(List<DictEntity3> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        mPopWindow.setBrandData(data);
    }

    public void setDistanceData(List<DictEntity3> data) {
        this.mDistanceData = data;
        distanceWindow5.setData(data);
        mPopWindow.setDistanceData(data);
    }

    public void setMaterialBrandData(List<MaterChooseEntity> data) {
        if (type == 0) {
            mRecommendMatterChooseAdapter.setDatas(data);
        } else {
            mMatterChooseAdapter.setDatas(data);
        }

        List<DictEntity3> list = new ArrayList<>();
        for (MaterChooseEntity datum : data) {
            List<DictEntity3> list1 = new ArrayList<>();
            for (MaterChooseEntity.TypeBean typeBean : datum.getType()) {
                list1.add(new DictEntity3(typeBean.getCid(), typeBean.getCname()));
            }
            list.add(new DictEntity3(datum.getId(), datum.getName(), list1));
        }
        mPopWindow.setSpecData(list);
    }

    public void setCurrentItem(String position, String threeId, String nameId, String fourId) {
//        mBinding.tlFragmentGoodsMainGoodsSelectTitle1.setScrollPosition(position, 0, true);
//        for (int i = 0; i < mTwo.size(); i++) {
//            if (threeId.equals(mTwo.get(i).getId())) {
//                mBinding.tlFragmentGoodsMainGoodsSelectTitle2.setScrollPosition(i, 0, true);
//            }
//        }
        isStartAct1 = true;
        isStartAct2 = true;
        mOneType = position;
        mTwoType = threeId;
        mThreeType = fourId;
        for (int i = 0; i < mGoodsType.size(); i++) {
            if (mGoodsType.get(i).getId().equals(mOneType)) {
                int finalI = i;
                if (mBinding.tlFragmentGoodsMainGoodsSelectTitle1.getTabAt(finalI).isSelected()) {
                    setCurrentTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.getTabAt(finalI));
                } else {
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle1.postDelayed(() -> Objects.requireNonNull(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.getTabAt(finalI)).select(), 100);
                }
            }
        }
        mSelectTab = 1;
        mModel.getTwoOrThreeLevelData(mOneType);
        mBinding.tvFragmentGoodsMainGoodsListSelect2.setVisibility(View.VISIBLE);
    }

    /***
     * 设置二三级数据
     * @param threeLevelData
     */
    public void setTwoOrThreeLevelData(List<TwoOrThreeLevelEntity> threeLevelData) {
        if (mSelectType == 0) {
            mBinding.tlFragmentGoodsMainGoodsSelectTitle2.removeAllTabs();
        } else {
            mBinding.tlFragmentGoodsMainGoodsSelectTitle3.removeAllTabs();
        }

        if (mSelectType == 0) {
            mTwo = threeLevelData;
            List<DictEntity3> data = new ArrayList<>();
            if (mSelectTab == 1) {
                for (int i = 0; i < threeLevelData.size(); i++) {
                    TwoOrThreeLevelEntity threeLevelDatum = threeLevelData.get(i);
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle2.addTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle2.newTab().setText(threeLevelDatum.getName()));
                    data.add(new DictEntity3(threeLevelDatum.getId(), threeLevelDatum.getName()));
                    if (!TextUtils.isEmpty(mTwoType)) {
                        if (threeLevelDatum.getId().equals(mTwoType) && isStartAct1) {
                            isStartAct1 = false;
                            mBinding.tlFragmentGoodsMainGoodsSelectTitle2.setScrollPosition(i, 0, true, true);
                        }
                    }
                }
            } else {
                for (TwoOrThreeLevelEntity threeLevelDatum : threeLevelData) {
                    data.add(new DictEntity3(threeLevelDatum.getId(), threeLevelDatum.getName()));
                }

            }
            mPopWindow.setTypeData(data);
            if (threeLevelData.size() > 0) {
                mBinding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.VISIBLE);
                mBinding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.VISIBLE);
            } else {
                mBinding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.GONE);
                mBinding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.GONE);
            }
        } else {
            mThree = threeLevelData;
            List<DictEntity3> data = new ArrayList<>();
            if (mSelectTab == 1) {
                for (int i = 0; i < threeLevelData.size(); i++) {
                    TwoOrThreeLevelEntity threeLevelDatum = threeLevelData.get(i);
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle3.addTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle3.newTab().setText(threeLevelDatum.getName()));
                    data.add(new DictEntity3(threeLevelDatum.getId(), threeLevelDatum.getName()));
                    if (threeLevelDatum.getId().equals(mThreeType) && isStartAct2) {
                        isStartAct2 = false;
                        mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setScrollPosition(i, 0, true, true);
                        mModel.getMaterialBrand(mThreeType);
                    }
                }
            } else {
                for (TwoOrThreeLevelEntity threeLevelDatum : threeLevelData) {
                    data.add(new DictEntity3(threeLevelDatum.getId(), threeLevelDatum.getName()));
                }
            }
            mPopWindow.setNameData(data);
            if (mThree != null && mThree.size() > 0) {
                mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.VISIBLE);
                mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.VISIBLE);
            } else {
                mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
                mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
            }
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.ll_content:
                if (isZiYingChecked) {
                    mBinding.llContent.setBackground(requireActivity().getResources().getDrawable(R.drawable.search_bg));
                    mBinding.btnZiying.setTextColor(requireActivity().getResources().getColor(com.swgk.core.R.color.color_333333));
                } else {
                    mBinding.llContent.setBackground(requireActivity().getResources().getDrawable(R.drawable.search_new_blue_bg));
                    mBinding.btnZiying.setTextColor(requireActivity().getResources().getColor(com.swgk.core.R.color.color_main));
                }
                isZiYingChecked = !isZiYingChecked;

                if (type == 0) {
                    loadRecommendList(false);
                } else {
                    loadAllList(false);
                }
                break;
            case R.id.iv_goods_list_search:
                searchClick();
                break;
            default:
                break;
        }
    }

    public void loadRecommendList(boolean isLoadMore) {
        isLoadMoreRecommendGoodsList = isLoadMore;
        mRecommendPageNum = isLoadMore ? mRecommendPageNum + 1 : 0;

        StringBuilder stringBuilder = new StringBuilder();
        for (String s : mAreaId) {
            stringBuilder.append(",").append(s);
        }
        stringBuilder.replace(0, 1, "");
        Map<String, Object> map = new HashMap<>();
        map.put("province", mProvince);
        map.put("city", mCityId);
        map.put("area", stringBuilder.toString());
        map.put("page", mRecommendPageNum);
        map.put("size", 10);
        map.put("valId", mRecommendValId);
        map.put("item_cid1", mItemCid1);
        map.put("item_cid2", mItemCid2);
        map.put("item_cid", mItemCid3);
        if (isZiYingChecked) {
            map.put("selfSupportTag", 1);
        }
        mModel.getRecommendList(map);
    }

    public void loadAllList(boolean isLoadMore) {
        Map<String, Object> map = new HashMap<>(8);
        if (isSellGoodGoods) {
            map.put("cid1", mCid1);
            map.put("categoryId", mCategoryId);
            map.put("cid3", mCid3);
            map.put("sortType", 1);
            map.put("asc", false);
            map.put("spu", true);
            map.put("pageNum", 1);
            map.put("pageSize", 50);
            if (LocationUtil.isOpenLocation(getContext()) && LocationUtil.currentLocationIsValid()) {
                map.put("lon", String.valueOf(LocationUtil.getCurrentLongitude()));
                map.put("lat", String.valueOf(LocationUtil.getCurrentLatitude()));
            } else {
                map.put("lon", "0");
                map.put("lat", "0");
            }
            mModel.getGoodsList(map);
        } else if (isPromotionalGoods) {
            isLoadMoreGoodsList = isLoadMore;
            mPageNum = isLoadMore ? mPageNum + 1 : 1;
            map.put("pageNum", mPageNum);
            map.put("pageSize", 20);
            map.put("text", "");
            map.put("distance", mDistance);
            map.put("priceSort", mPriceSort);
            if (!"0".equals(mPriceSort)) {
                map.put("timeSort", "0");
            } else {
                map.put("timeSort", "2");
            }
            map.put("cid1", mCid1);
            map.put("cid3", mCid3);
            map.put("categoryId", mCategoryId);
            String mItemId = "";
            map.put("itemId", mItemId);
            map.put("brandId", mBrandId);
            map.put("materValue", StringUtil.formatListToString(mMaterValue));
            map.put("regionCode", mAreaId);
            map.put("areaId", mCityId);
            if (isZiYingChecked) {
                map.put("selfSupportTag", 1);
            }
            map.put("promoteStatus", 2);
            map.put("areaCode", mProvince);
            if (LocationUtil.isOpenLocation(getContext()) && LocationUtil.currentLocationIsValid()) {
                if (!isRePositioning) {
                    map.put("lon", String.valueOf(LocationUtil.getCurrentLongitude()));
                    map.put("lat", String.valueOf(LocationUtil.getCurrentLatitude()));
                } else {
                    map.put("lon", mLon);
                    map.put("lat", mLat);
                }
            } else {
                map.put("lon", "0");
                map.put("lat", "0");
            }
            mModel.getGoodsList(map);
        }
    }

    public void getGoodsList(List<GoodsListEntity> dataA) {
        List<GoodsListEntity> data = new ArrayList<>();
        int ranking = 1;
        if (isPromotionalGoods) {
            for (GoodsListEntity datum : dataA) {
                if (datum.getPromoteStatus() == 2) {
                    data.add(datum);
                }
            }
        } else if (isSellGoodGoods) {
            for (GoodsListEntity datum : dataA) {
                datum.setSellGoodGoods(true);
                datum.setRanking(ranking);
                data.add(datum);
                ranking++;
            }
        }

        mBinding.xrvFragmentGoodsMainGoodsList.refreshComplete();
        if (isLoadMoreGoodsList) {
            if (data.size() > 0) {
                mBinding.xrvFragmentGoodsMainGoodsList.loadMoreComplete();
                mMaterialAdapter.addDatas(data);
            } else {
                mBinding.xrvFragmentGoodsMainGoodsList.setNoMore(true);
            }
            mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
        } else {
            mBinding.xrvFragmentGoodsMainGoodsList.refreshComplete();
            if (data.size() > 0) {
                mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
                mBinding.emptyView.setVisibility(View.GONE);
                mMaterialAdapter.setDatas(data);
                mBinding.xrvFragmentGoodsMainGoodsList.setLoadingMoreEnabled(true);
            } else {
                mMaterialAdapter.setDatas(null);
                mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.GONE);
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MaterialEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MATERIAL_FILTER) {
            String text = (String) event.getMessageData();
            Objects.requireNonNull(mModel.materialFilterJson.get()).setText(text);
            loadAllList(false);
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_LOC) {
            mLon = (String) event.getObject();
            mLat = (String) event.getMessageData();
            Objects.requireNonNull(mModel.materialFilterJson.get()).setLat(mLat);
            Objects.requireNonNull(mModel.materialFilterJson.get()).setLon(mLon);
        }
    }


    public void getRecommendList(List<RecommendListEntity> data) {
        if (isLoadMoreRecommendGoodsList) {
            if (null != data && data.size() > 0) {
                mBinding.xrvFragmentGoodsMainGoodsList.loadMoreComplete();
                mRecommendGoodsAdapter.addDatas(data);
            } else {
                mBinding.xrvFragmentGoodsMainGoodsList.setNoMore(true);
            }
            mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
        } else {
            mBinding.xrvFragmentGoodsMainGoodsList.refreshComplete();
            if (null != data && data.size() > 0) {
                mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
                mBinding.emptyView.setVisibility(View.GONE);
                mRecommendGoodsAdapter.setDatas(data);
                mBinding.xrvFragmentGoodsMainGoodsList.setLoadingMoreEnabled(true);
            } else {
                mRecommendGoodsAdapter.setDatas(null);
                mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.GONE);
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setTextViewBg(TextView textView, int bg, int img, int textColor) {
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());  //此为必须写的
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_fragment_goods_main_goods_list_select2:
                mBinding.tvFragmentGoodsMainGoodsListSelect2.contentSelectRed(false, true);
                distanceWindow5.showPopwindow(mBinding.nsvSelect, 0, 0);
                break;
            case R.id.tv_fragment_goods_main_goods_list_select1:
                mBinding.tvFragmentGoodsMainGoodsListSelect1.contentSelectRed(false, true);
                mThreeLevelPopWindow.showPopwindow(mBinding.nsvSelect, 0, 0);
                break;
            case R.id.tv_goods_list_screen:
                EventBus.getDefault().post(LeaseEvent.make().setMessageTag(EventConstant.EVENT_SHOP_GONE));
                if (mTwo != null && mTwo.size() > 0) {
                    mPopWindow.setTypeDefault(mBinding.tlFragmentGoodsMainGoodsSelectTitle2.getSelectedTabPosition(), mCategoryId);
                } else {
                    mModel.getTwoOrThreeLevelData(mCid1);
                    mSelectType = 0;
                }

                if (mThree != null && mThree.size() > 0) {
                    mPopWindow.showListVisible(mBinding.tlFragmentGoodsMainGoodsSelectTitle3.getSelectedTabPosition());
                }

                if (mDistanceData != null && mDistanceData.size() > 0) {

                } else {
                    if (!"".equals(mCid1)) {
                        mModel.getFilterDistance(mCid1);
                    }
                }

                if (mAreaList.size() <= 0) {
                    mModel.getAreaData();
                }

                mPopWindow.showPopwindowRight((GoodsAggregateActivity.getPopView()));
                break;
            case R.id.img_back_top:
                mBinding.xrvFragmentGoodsMainGoodsList.smoothScrollToPosition(0);
                break;
        }
    }

    public void getItemChoose(List<DictEntity3> data) {
        mPopWindow.setSpecData(data);
    }

    public void setAddressData
            (List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String
                    areaCode) {
        this.mAreaList = data;
        mThreeLevelPopWindow.setData(data, true, areaCode);
    }

    public void showPriceSort(List<DictEntity3> list) {
        mPopWindow.setPriceData(list);
    }

    public void getAreaChoose(List<AreaChooseEntity> list) {
        List<DictEntity3> list1 = new ArrayList<>();
        for (AreaChooseEntity areaChooseEntity : list) {
            list1.add(new DictEntity3(areaChooseEntity.getId(), areaChooseEntity.getAreaName()));
        }
        mPopWindow.setAreaData(list1);
    }

    private void searchClick() {
        if (isPromotionalGoods) {
            HomeCategoryActivity.start(getActivity(), RequestCode.REQUEST_SHOP_PROMOTION);
        } else if (isSellGoodGoods) {
            HomeCategoryActivity.start(getActivity(), RequestCode.REQUEST_SHOP_SELL_GOOD);
        }
    }

    private void setCurrentTab(TabLayout.Tab tab) {
        if (tab.getPosition() == 0) {
            mBinding.rlGoodMatterChoose.setVisibility(View.GONE);
            mBinding.rvGoodMatterChoose.setVisibility(View.GONE);
            if (type == 0) {
                mItemCid1 = "";
                mItemCid2 = "";
                mItemCid3 = "";
                mRecommendValId = "";
            } else {
                mCid1 = "";
                mCid3 = "";
                mCategoryId = "";
                mMaterValue.clear();
            }
            mDistance = "";
        }
        String cid;
        if (type == 0) {
            mItemCid1 = mGoodsType.get(tab.getPosition()).getId();
            loadRecommendList(false);
            cid = mItemCid1;
        } else {
            mCid1 = mGoodsType.get(tab.getPosition()).getId();
            cid = mCid1;
        }

        if (type == 0) {
            loadRecommendList(false);
        } else {

            loadAllList(false);
        }
        if (tab.getPosition() == 0) {
            mBinding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.GONE);
            mBinding.tvFragmentGoodsMainGoodsListSelect2.setVisibility(View.GONE);
            mBinding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.GONE);
            mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
        } else {
            mBinding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.VISIBLE);
            mBinding.tvFragmentGoodsMainGoodsListSelect2.setVisibility(View.VISIBLE);
            mBinding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.VISIBLE);
            mModel.getFilterDistance(cid);
            mModel.getTwoOrThreeLevelData(cid);
        }
        mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
        mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
        mSelectType = 0;
        mSelectTab = 1;
    }
}
